package com.flower.gateway;

import com.common.utils.CloudConstant;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.Base64Utils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @ClassName AuthFilter
 * @Description 网关统一认证中心
 * @Author 吃麻椒的花酱
 * @Date 2022/4/3 2:42
 * @Version 1.0
 */
@Configuration
public class AuthFilter implements GlobalFilter, Ordered  {
    // ServerWebExchange就相当于当前请求和响应的上下文
    //ServerWebExchange实例不单存储了Request和Response对象，还提供了一些扩展方法，如果想实现改造请求参数或者响应参数，就必须深入了解ServerWebExchange
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        byte[] token = Base64Utils.encode((CloudConstant.GATEWAY_TOKEN_VALUE).getBytes());
        String[] token_value = {new String(token)};
        //获取请求数据源对象 添加额外Token 防止绕过网关访问服务
        ServerHttpRequest mutate = request.mutate().header(CloudConstant.GATEWAY_TOKEN_HEADER,token_value).build();
        ServerWebExchange newExchange=exchange.mutate().request(mutate).build();
        return chain.filter(newExchange);
    }

    @Override
    public int getOrder() {
        return 100;
    }
}
